package cancer

import (
	"encoding/json"
	"fmt"
	"gitcode.com/G-YT/ANN/server/global"
	"gitcode.com/G-YT/ANN/server/model/cancer"
	cancerRes "gitcode.com/G-YT/ANN/server/model/cancer/response"
)

type CancerService struct{}

// GetCancerQuestions 获取癌症问题列表
func (cancerService *CancerService) GetCancerQuestions() (list []cancer.Questions, err error) {
	err = global.GVA_DB.Preload("Cancer").Find(&list).Error
	return
}

// CreateCancerOptions 创建癌症选项集
func (cancerService *CancerService) CreateCancerOptions(info *cancer.Options) (err error) {
	err = global.GVA_DB.Create(info).Error
	return
}

// GetCancerOptionsByUid 获取用户癌症选项集
func (cancerService *CancerService) GetCancerOptionsByUid(uid uint) (info cancer.Options, err error) {
	err = global.GVA_DB.Where("uid = ?", uid).First(&info).Error
	return
}

// UpdateCancerOptions 更新用户健康管理标签
func (cancerService *CancerService) UpdateCancerOptions(id uint, co *cancer.Options) (err error) {
	err = global.GVA_DB.Model(&cancer.Options{}).Where("id = ?", id).Updates(co).Error
	return
}

// GetScreenReport 获取筛查报告
func (cancerService *CancerService) GetScreenReport(uid uint) (list []cancerRes.ScreenReport, err error) {
	var cancers []cancer.Cancer
	var questions []cancer.Questions
	var options cancer.Options
	if optionsErr := global.GVA_DB.First(&options, "uid = ?", uid).Error; optionsErr != nil {
		return nil, optionsErr
	}
	var optionList []string
	if jsonErr := json.Unmarshal(options.Options, &optionList); jsonErr != nil {
		return nil, jsonErr
	}
	// 获取全部癌症
	if cancersErr := global.GVA_DB.Find(&cancers).Error; cancersErr != nil {
		return nil, cancersErr
	}
	// 获取全部问题
	if questionsErr := global.GVA_DB.Find(&questions).Error; questionsErr != nil {
		return nil, questionsErr
	}
	// 按癌症类型分组
	cancerQuestionsMap := make(map[uint][]uint)
	for _, q := range questions {
		cancerQuestionsMap[q.Cid] = append(cancerQuestionsMap[q.Cid], q.ID)
	}
	// 计算得分
	for cancerID, questionIDs := range cancerQuestionsMap {
		// 计算基础得分
		numQuestions := len(questionIDs)
		if numQuestions == 0 {
			continue
		}
		baseScorePerQuestion := 80.0 / uint(numQuestions)
		// 用户的基础得分
		var userScore uint
		for _, qID := range questionIDs {
			for _, optID := range optionList {
				if fmt.Sprintf("%d", qID) == optID {
					userScore += baseScorePerQuestion
					break
				}
			}
		}
		// 计算其他得分
		otherScore := 0
		if *options.IsInfect {
			otherScore += 10
		}
		if *options.IsInject {
			otherScore += 10
		}
		// 总得分
		totalScore := userScore + uint(otherScore)
		cancerName := ""
		if cancerNameErr := global.GVA_DB.Model(&cancer.Cancer{}).Where("id = ?", cancerID).Select("name").Scan(&cancerName).Error; cancerNameErr != nil {
			return nil, cancerNameErr
		}
		list = append(list, cancerRes.ScreenReport{Name: cancerName, Value: totalScore})
	}
	return
}
